<?php

/**
   * lib.mysql -- Emergine MySQL library
   * @version: 1.0
   * @author: Hleb Piatrou <h.piatrou@softteco.com>
   * @link: http://code.google.com/p/emergine/
   * @copyright: Copyright 2011-2012 Hleb Piatrou
   * @license: MIT License http://www.opensource.org/licenses/mit-license.php
   * @interface: Common Model Interface (CMI)
   */

/**
   * Additional libs inclusion
   * @lib.settings: Emergine Models Library
   */
   
include_once "./libraries/lib.models.php";

/* Using additional namespaces */

	use Emergine\Libs\Models as Models;	
	use Emergine\Libs\Settings as Settings;

/**
   * Emergine MySQL class
   * 
   * This class can be used to generate SQL-queries for MySQL DB server.
   * 
   * Example of usage:
   * <code>
   * MySQL::CreateTable(); // returns the CREATE TABLE construction
   * MySQL::AlterTable(); // returns the ALTER TABLE construction
   * MySQLLLFieldType(0,1) // returns the type of 2nd field of 1st table
   * </code>
   * @dependencies: lib.models.php
   * @interface: Common Model Interface (CMI)
   */
   	
	class MySQL extends Models
    {
		/**
		 * @access: public
		 * @param: none
		 * @return: none
		 */	
		public function Connect()
		{
			$connection = mysql_connect(Settings::DBOptions("hostname"), 
			                            Settings::DBOptions("username"), 
			                            Settings::DBOptions("password"));
			$database = mysql_select_db(Settings::DBOptions("dbname"));
			return $connection;
		}
		/**
		 * @access: public
		 * @param: none
		 * @return: none
		 */	
		public function SyncDB()
		{
			MySQL::CreateTable();
			MySQL::Connect();
            $fileContent = file_get_contents("./cache/mysql.models.sql");
            $sqlArray = explode(';', $fileContent);
            foreach ($sqlArray as $sql)
            {
				mysql_query($sql);
			}
		}		
		/**
		 * @access: public
		 * @param: none
		 * @return: none
		 */	
		public function CreateTable()
		{
			$fp = fopen("./cache/mysql.models.sql", "w");
			$table_count = count(parent::ArrayContent());
			for ($i = 0; $i<$table_count; $i++)
			{
				$field_count = count(parent::TableContent($i));
				$query1 = "CREATE TABLE ".Models::TableName($i)." (\n";
				fwrite($fp, $query1);
				
				for ($j=0; $j<$field_count; $j++)
				{
					$query2 = parent::Field($i, $j)." ".MySQL::FieldType($i, $j).",\n";
					fwrite($fp, $query2);
				}
				
				$query3 = "PRIMARY KEY(id));\n\n";
				fwrite($fp, $query3);
			}
		fclose($fp);
		}
		/**
		 * @access: public
		 * @param: none
		 * @return: none
		 */			
		public function AlterTable()
		{
			$fp = fopen("./cache/dbconfig.sql", "w");
			$table_count = count((array)parent::ArrayContent());
			for ($i = 0; $i<$table_count; $i++)
			{
				$field_count = count(parent::TableContent($i));
				$query1 = "ALTER TABLE ".parent::TableName($i)." (\n";
				fwrite($fp, $query1);
				for ($j=0; $j<$field_count; $j++)
				{
					$query2 = parent::Field($i, $j)." ".MySQL::FieldType($i, $j).",\n";
					fwrite($fp, $query2);
				}
				$query3 = "PRIMARY KEY(id));\n\n";
				fwrite($fp, $query3);
			}
		fclose($fp);
		}
		/**
		 * @access: public
		 * @param: int $table_undex - the number of table, int $index - the number of field
		 * @return: string
		 */	
		 public function FieldType($table_index, $index)
		 {	
			if (parent::FieldType($table_index, $index) == "AutoField")
			{
				$field['type'] = "INT NOT NULL AUTO_INCREMENT";
				$field['value'] = null;
				$field['summary'] = $field['type'];
			}
			
			if (parent::FieldType($table_index, $index) == "IntegerField")
			{
				$field['type'] = "INT";
				$field['value'] = parent::MaxValue($table_index, $index);
				$field['summary'] = $field['type']."(".$field['value'].") NOT NULL";
			}
			
			if (parent::FieldType($table_index, $index) == "CharField")
			{
				$field['type'] = "VARCHAR";
				$field['value'] = parent::MaxValue($table_index, $index);
				$field['summary'] = $field['type']."(".$field['value'].") NOT NULL";
			}
			return $field['summary'];
		}
		/**
		 * @access: public
		 * @param: object $param - an object of inserted keys and values
		 * @return: none
		 */			
		public function Insert($param)
		{
			$cache = fopen("./cache/mysql.models.sql", "w");
			$query_part1 = "INSERT INTO ".$param->table." (";
			fwrite($cache, $query_part1);
			unset($param->table);
			$table_values = array_values((array)$param);
			$table_keys = array_keys((array)$param);
			for ($i=0;$i<count($table_values); $i++)
			{
				if ($i == count($table_values)-1)
				{
					$query_part2[$i] = $table_keys[$i];	
				}
				else
				{
					$query_part2[$i] = $table_keys[$i].', ';
				}
				fwrite($cache, $query_part2[$i]);
			}
			$query_part3 = ") VALUES (";
			fwrite($cache, $query_part3);
			for ($i=0;$i<count($table_values); $i++)
			{
				if ($i == count($table_values)-1)
				{
					$query_part4[$i] = "'".$table_values[$i]."');";	
				}
				else
				{
					$query_part4[$i] = "'".$table_values[$i]."',";
				}
				fwrite($cache, $query_part4[$i]);
			}
		}
		/**
		 * @access: public
		 * @param: object $param - an object of inserted keys and values
		 * @return: none
		 */		
		 public function Select($table)
		 {
			$cache = fopen("./cache/mysql.models.sql", "w");
			$query = "SELECT * FROM ".$table.";";
			fwrite($cache, $query);
		 }
	}	 
?>

